package com.sky.loveshop.service.impl;

import com.sky.loveshop.entity.MqttClientEntity;
import com.sky.loveshop.mapper.MqttClientMapper;
import com.sky.loveshop.service.MqttClientService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author xcy
 * @version V1.0
 * @description
 * @date 2024/11/17 20:52
 */
@Slf4j
@Service
public class MyMqttClientServiceImpl implements MqttClientService {

    @Resource
    private MqttClientMapper mqttClientMapper;
    @Value("${spring.profiles.active}")
    private String activeProfile;


    @Override
    public List<MqttClientEntity> listAll() {
        return mqttClientMapper.selectAll();
    }

    @Override
    public List<MqttClientEntity> listAllByEnv() {
        Example example = new Example(MqttClientEntity.class);
        example.createCriteria().andEqualTo("env", activeProfile)
                .andEqualTo("type", "pub");
        return mqttClientMapper.selectByExample(example);
    }

    @Override
    public String getPublisher(Integer shopId) {
        // 查询当前环境用来发送指令的客户端，即type=pub的，保证一个环境下只能有一个pub，其他的sub可以有多个
        Example example = new Example(MqttClientEntity.class);
        example.createCriteria()
                .andEqualTo("env", activeProfile)
                .andEqualTo("type", "pub")
                .andEqualTo("shopId", shopId)
        ;
        MqttClientEntity mqttClientEntity = mqttClientMapper.selectOneByExample(example);
        return mqttClientEntity.getClientId();
    }
}
